package com.charlygao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import logbook.server.proxy.ProxyServer;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;

import com.charlygao.script.Kcs;

public class MainWindow
{
	public static final Display display = new Display();
	public static final Shell shellShip = new Shell(display, SWT.CLOSE | SWT.MIN | SWT.SYSTEM_MODAL);
	
	public static final Group grpParameters = new Group(shellShip, SWT.NONE);
	public static final Button btnKCTools = new Button(grpParameters, SWT.NONE);
	public static final Label lblTokenStatus = new Label(grpParameters, SWT.LEFT);
	public static final Label lblVersionStatus = new Label(grpParameters, SWT.LEFT);
	public static final Label lblFleetMission2 = new Label(grpParameters, SWT.LEFT);
	public static final Label lblFleetMission3 = new Label(grpParameters, SWT.LEFT);
	public static final Label lblFleetMission4 = new Label(grpParameters, SWT.LEFT);
	public static final Label lblFleetMission2Kira = new Label(grpParameters, SWT.LEFT);
	public static final Label lblFleetMission3Kira = new Label(grpParameters, SWT.LEFT);
	public static final Label lblFleetMission4Kira = new Label(grpParameters, SWT.LEFT);
	public static final Label lblAutoBattle = new Label(grpParameters, SWT.LEFT);
	public static final Label lblAutoKira = new Label(grpParameters, SWT.LEFT);
	public static final Label lblAutoRes = new Label(grpParameters, SWT.LEFT);
	public static final Label lblAutoSteel = new Label(grpParameters, SWT.LEFT);
	
	public static final Text txtFleetMission2 = new Text(grpParameters, SWT.LEFT | SWT.BORDER);
	public static final Text txtFleetMission3 = new Text(grpParameters, SWT.LEFT | SWT.BORDER);
	public static final Text txtFleetMission4 = new Text(grpParameters, SWT.LEFT | SWT.BORDER);
	public static final Button btnFleetKira2 = new Button(grpParameters, SWT.CHECK);
	public static final Button btnFleetKira3 = new Button(grpParameters, SWT.CHECK);
	public static final Button btnFleetKira4 = new Button(grpParameters, SWT.CHECK);
	public static final Button btnAutoBattle = new Button(grpParameters, SWT.CHECK);
	public static final Button btnAutoKira = new Button(grpParameters, SWT.CHECK);
	public static final Button btnAutoRes = new Button(grpParameters, SWT.CHECK);
	public static final Button btnAutoSteel = new Button(grpParameters, SWT.CHECK);
	public static final Button btnStart = new Button(grpParameters, SWT.NONE);
	
	public static final TabFolder tabFolder = new TabFolder(shellShip, SWT.NULL);
	public static final TabItem tabLog = new TabItem(tabFolder, SWT.NULL);
	public static final TabItem tabCount = new TabItem(tabFolder, SWT.NULL);
	public static final TabItem tabExp = new TabItem(tabFolder, SWT.NULL);
	
	public static final Composite cmpExp = new Composite(tabFolder, SWT.BORDER);
	public static final Label lblExpOriginalLevel = new Label(cmpExp, SWT.LEFT);
	public static final Label lblExpTargetLevel = new Label(cmpExp, SWT.LEFT);
	public static final Label lblExpPosition = new Label(cmpExp, SWT.LEFT);
	public static final Label lblExpCount = new Label(cmpExp, SWT.LEFT);
	public static final Text txtExpOriginalLevel = new Text(cmpExp, SWT.LEFT | SWT.BORDER);
	public static final Text txtExpTargetLevel = new Text(cmpExp, SWT.LEFT | SWT.BORDER);
	public static final Combo cboExpPosition = new Combo(cmpExp, SWT.LEFT | SWT.READ_ONLY);
	
	public static final Composite cmpCount = new Composite(tabFolder, SWT.BORDER);
	public static final Label lblCountStartTime = new Label(cmpCount, SWT.LEFT);
	public static final Label lblCountEclipseTime = new Label(cmpCount, SWT.LEFT);
	public static final Label lblCountWin = new Label(cmpCount, SWT.LEFT);
	public static final Label lblCountLose = new Label(cmpCount, SWT.LEFT);
	public static final Label lblCountBP = new Label(cmpCount, SWT.LEFT);
	public static final Label lblCountOil = new Label(cmpCount, SWT.LEFT);
	public static final Label lblCountAmmo = new Label(cmpCount, SWT.LEFT);
	public static final Label lblCountSteel = new Label(cmpCount, SWT.LEFT);
	public static final Label lblCountAlum = new Label(cmpCount, SWT.LEFT);
	public static final Label lblCountBucket = new Label(cmpCount, SWT.LEFT);
	public static final Label lblCountBuild = new Label(cmpCount, SWT.LEFT);
	public static final Button btnCountModeSwitch = new Button(cmpCount, SWT.NONE);
	public static final Button btnCountReset = new Button(cmpCount, SWT.NONE);
	public static int bCountSwitchMode = 0;
	
	//public static final Group grpLog = new Group(shellShip, SWT.NONE);
	public static final Text txtLog = new Text(tabFolder, SWT.MULTI | SWT.READ_ONLY | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
	
	
	
	public static ArrayList<String> log;
	public static Timer timerLogUpdate;
	public static Timer timerStatusUpdate;

	public static Thread thread;
	
	public static Kcs kcs = new Kcs();
	
	public static void buildShipInit()
	{
		if (btnStart.getText().equals("开始"))
		{
			btnStart.setEnabled(false);
			kcs.auto_mode = btnAutoBattle.getSelection()?1:0;
			kcs.auto_kira = btnAutoKira.getSelection()?1:0;
			kcs.auto_res = btnAutoRes.getSelection()?1:0;
			kcs.auto_steel = btnAutoSteel.getSelection()?1:0;
			kcs.fleet_mission_map[2] = Integer.parseInt(txtFleetMission2.getText());
			kcs.fleet_mission_map[3] = Integer.parseInt(txtFleetMission3.getText());
			kcs.fleet_mission_map[4] = Integer.parseInt(txtFleetMission4.getText());
			kcs.fleet_mission_kira[2] = btnFleetKira2.getSelection()?1:0;
			kcs.fleet_mission_kira[3] = btnFleetKira3.getSelection()?1:0;
			kcs.fleet_mission_kira[4] = btnFleetKira4.getSelection()?1:0;
			for (int check : kcs.fleet_mission_kira)
				if (check == 1)
					kcs.auto_mission = 1;

    		thread = new Thread(kcs);
    		thread.start();
    		btnStart.setText("停止");
    		btnStart.setEnabled(true);
    		
    		timerLogUpdate = new Timer(true);
    		TimerTask logUpdateTask = new LogUpdateTask();
    		timerLogUpdate.schedule(logUpdateTask, 0, 500);
    		
    		PropertyHelper.writeProperties("fleet_mission_2", txtFleetMission2.getText());
    		PropertyHelper.writeProperties("fleet_mission_3", txtFleetMission3.getText());
    		PropertyHelper.writeProperties("fleet_mission_4", txtFleetMission4.getText());
    		PropertyHelper.writeProperties("fleet_mission_kira_2", btnFleetKira2.getSelection()?"1":"0");
    		PropertyHelper.writeProperties("fleet_mission_kira_3", btnFleetKira3.getSelection()?"1":"0");
    		PropertyHelper.writeProperties("fleet_mission_kira_4", btnFleetKira4.getSelection()?"1":"0");
		}
		else
		{
			btnStart.setEnabled(false);
			if (thread != null)
				thread.stop();
			btnStart.setText("开始");
			btnStart.setEnabled(true);
			timerLogUpdate.cancel();
		}
	}
	
	public static void log(String content) 
	{
		SimpleDateFormat formatter = new SimpleDateFormat("[HH:mm:ss] ");
		Date curDate = new Date(System.currentTimeMillis());
		String timestamp = formatter.format(curDate);
		log.add(timestamp + content);
	}
	
	public static void main(String[] args) throws InterruptedException 
	{
		shellShip.setBounds(300, 300, 500, 290);
		shellShip.setText("KCScript 2.3 by charlygao");
    	
    	grpParameters.setBounds(10, 10, 160, 240);
    	grpParameters.setText("设定");
    	
    	lblTokenStatus.setBounds(10, 30, 65, 20);
    	lblTokenStatus.setText("Token: NO");
    	lblVersionStatus.setBounds(80, 30, 70, 20);
    	lblVersionStatus.setText("Ver: NULL");
    	lblFleetMission2.setBounds(10, 60, 40, 20);
    	lblFleetMission2.setText("舰队2：");
    	lblFleetMission3.setBounds(10, 90, 40, 20);
    	lblFleetMission3.setText("舰队3：");
    	lblFleetMission4.setBounds(10, 120, 40, 20);
    	lblFleetMission4.setText("舰队4：");
    	lblFleetMission2Kira.setBounds(110, 60, 20, 20);
    	lblFleetMission2Kira.setText("闪");
    	lblFleetMission3Kira.setBounds(110, 90, 20, 20);
    	lblFleetMission3Kira.setText("闪");
    	lblFleetMission4Kira.setBounds(110, 120, 20, 20);
    	lblFleetMission4Kira.setText("闪");
    	btnFleetKira2.setBounds(130, 60, 20, 20);
    	btnFleetKira3.setBounds(130, 90, 20, 20);
    	btnFleetKira4.setBounds(130, 120, 20, 20);
    	lblAutoBattle.setBounds(10, 150, 40, 20);
    	lblAutoBattle.setText("练级：");
    	lblAutoKira.setBounds(90, 150, 40, 20);
    	lblAutoKira.setText("刷闪：");
    	lblAutoRes.setBounds(10, 180, 40, 20);
    	lblAutoRes.setText("偷油：");
    	lblAutoSteel.setBounds(90, 180, 40, 20);
    	lblAutoSteel.setText("捞钢：");
    	
    	txtFleetMission2.setBounds(55, 60, 50, 20);
    	if (PropertyHelper.getKeyValue("fleet_mission_2") != null)
    		txtFleetMission2.setText(PropertyHelper.getKeyValue("fleet_mission_2"));
    	txtFleetMission3.setBounds(55, 90, 50, 20);
    	if (PropertyHelper.getKeyValue("fleet_mission_3") != null)
    		txtFleetMission3.setText(PropertyHelper.getKeyValue("fleet_mission_3"));
    	txtFleetMission4.setBounds(55, 120, 50, 20);
    	if (PropertyHelper.getKeyValue("fleet_mission_4") != null)
    		txtFleetMission4.setText(PropertyHelper.getKeyValue("fleet_mission_4"));
    	
    	if (PropertyHelper.getKeyValue("fleet_mission_kira_2") != null)
    		btnFleetKira2.setSelection(PropertyHelper.getKeyValue("fleet_mission_kira_2").equals("1"));
    	if (PropertyHelper.getKeyValue("fleet_mission_kira_3") != null)
    		btnFleetKira3.setSelection(PropertyHelper.getKeyValue("fleet_mission_kira_3").equals("1"));
    	if (PropertyHelper.getKeyValue("fleet_mission_kira_4") != null)
    		btnFleetKira4.setSelection(PropertyHelper.getKeyValue("fleet_mission_kira_4").equals("1"));
    	
    	btnAutoBattle.setBounds(50, 150, 20, 20);
    	btnAutoBattle.setSelection(false);
    	btnAutoKira.setBounds(130, 150, 20, 20);
    	btnAutoKira.setSelection(false);
    	btnAutoRes.setBounds(50, 180, 20, 20);
    	btnAutoRes.setSelection(false);
    	btnAutoSteel.setBounds(130, 180, 20, 20);
    	btnAutoSteel.setSelection(false);
    	btnStart.setBounds(10, 205, 140, 30);
    	btnStart.setText("开始");
    	btnStart.setEnabled(false);
    	
    	//grpLog.setText("日志");
		//grpLog.setBounds(180, 10, 300, 240);
		//txtLog.setBounds(15, 25, 270, 205);
		log = new ArrayList<String>();
		
		tabFolder.setBounds(180, 10, 300, 240);
		tabLog.setText("日志");
		tabLog.setControl(txtLog);
		tabCount.setText("统计");
		tabCount.setControl(cmpCount);
		tabExp.setText("计算");
		tabExp.setControl(cmpExp);
		cmpExp.setBackground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
		cmpCount.setBackground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
		
		lblExpOriginalLevel.setBounds(15, 15, 60, 25);
		lblExpOriginalLevel.setText("当前等级：");
		lblExpTargetLevel.setBounds(160, 15, 60, 25);
		lblExpTargetLevel.setText("目标等级：");
		lblExpPosition.setBounds(15, 55, 60, 25);
		lblExpPosition.setText("练级方式：");
		lblExpCount.setBounds(160, 55, 100, 25);
		lblExpCount.setText("所需次数：");
		txtExpOriginalLevel.setBounds(75, 15, 30, 25);
		txtExpOriginalLevel.setText("1");
		txtExpTargetLevel.setBounds(225, 15, 30, 25);
		txtExpTargetLevel.setText("99");
		cboExpPosition.setBounds(75, 55, 70, 20);
		cboExpPosition.add("3-2FLG");
		cboExpPosition.add("3-2MVP");
		cboExpPosition.add("3-2NOR");
		cboExpPosition.select(0);
		ExpListener expListener = new ExpListener();
		expListener.modifyText(null);
		
		txtExpOriginalLevel.addModifyListener(expListener);
		txtExpTargetLevel.addModifyListener(expListener);
		txtExpOriginalLevel.addModifyListener(expListener);
		cboExpPosition.addModifyListener(expListener);
		
		lblCountStartTime.setBounds(10, 10, 200, 20);
		lblCountStartTime.setText("统计开始：XX-XX XX:XX:XX");
		lblCountEclipseTime.setBounds(10, 40, 150, 20);
		lblCountEclipseTime.setText("时间经过：XX.X小时");
		lblCountWin.setBounds(10, 70, 65, 20);
		lblCountWin.setText("胜：XXXXX");
		lblCountLose.setBounds(80, 70, 65, 20);
		lblCountLose.setText("负：XXXXX");
		lblCountBP.setBounds(150, 70, 65, 20);
		lblCountBP.setText("点：XXX");
		lblCountOil.setBounds(10, 100, 65, 20);
		lblCountOil.setText("油：XXXXX");
		lblCountAmmo.setBounds(80, 100, 65, 20);
		lblCountAmmo.setText("弹：XXXXX");
		lblCountSteel.setBounds(150, 100, 65, 20);
		lblCountSteel.setText("钢：XXXXX");
		lblCountAlum.setBounds(220, 100, 65, 20);
		lblCountAlum.setText("铝：XXXXX");
		lblCountBucket.setBounds(10, 130, 65, 20);
		lblCountBucket.setText("桶：XXX");
		lblCountBuild.setBounds(80, 130, 65, 20);
		lblCountBuild.setText("资：XXX");
		btnCountModeSwitch.setBounds(10, 160, 100, 30);
		btnCountModeSwitch.setText("表示切换");
		btnCountReset.setBounds(180, 160, 100, 30);
		btnCountReset.setText("重置统计");
		
		if (PropertyHelper.getKeyValue("fleet_status_start_time") != null)
			kcs.startTime = Long.parseLong(PropertyHelper.getKeyValue("fleet_status_start_time"));
		if (PropertyHelper.getKeyValue("fleet_status_win") != null)
			kcs.startWldata[0] = Integer.parseInt(PropertyHelper.getKeyValue("fleet_status_win"));
		if (PropertyHelper.getKeyValue("fleet_status_lose") != null)
			kcs.startWldata[1] = Integer.parseInt(PropertyHelper.getKeyValue("fleet_status_lose"));
		if (PropertyHelper.getKeyValue("fleet_status_bp") != null)
			kcs.startWldata[2] = Integer.parseInt(PropertyHelper.getKeyValue("fleet_status_bp"));
		if (PropertyHelper.getKeyValue("fleet_status_oil") != null)
			kcs.startResource[0] = Integer.parseInt(PropertyHelper.getKeyValue("fleet_status_oil"));
		if (PropertyHelper.getKeyValue("fleet_status_ammo") != null)
			kcs.startResource[1] = Integer.parseInt(PropertyHelper.getKeyValue("fleet_status_ammo"));
		if (PropertyHelper.getKeyValue("fleet_status_steel") != null)
			kcs.startResource[2] = Integer.parseInt(PropertyHelper.getKeyValue("fleet_status_steel"));
		if (PropertyHelper.getKeyValue("fleet_status_alum") != null)
			kcs.startResource[3] = Integer.parseInt(PropertyHelper.getKeyValue("fleet_status_alum"));
		if (PropertyHelper.getKeyValue("fleet_status_bucket") != null)
			kcs.startResource[5] = Integer.parseInt(PropertyHelper.getKeyValue("fleet_status_bucket"));
		if (PropertyHelper.getKeyValue("fleet_status_build") != null)
			kcs.startResource[6] = Integer.parseInt(PropertyHelper.getKeyValue("fleet_status_build"));
		kcs.updateCount();
		
		btnCountModeSwitch.addSelectionListener(new SelectionAdapter(){public void widgetSelected(SelectionEvent event)
    	{
    		bCountSwitchMode = (bCountSwitchMode == 1)?0:1;
    		kcs.updateCount();
    	}});
		
		btnCountReset.addSelectionListener(new SelectionAdapter(){public void widgetSelected(SelectionEvent event)
    	{
    		kcs.resetCount();
    		try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		kcs.updateCount();
    	}});
		
		
    	btnStart.addSelectionListener(new SelectionAdapter(){public void widgetSelected(SelectionEvent event)
    	{
    		buildShipInit();
    	}});
    	
    	SystemHotKey hotkey = new SystemHotKey();
    	hotkey.init();
    	
    	ProxyServer proxyServer = ProxyServer.getInstance(8999);
    	proxyServer.start();
    	
    	timerStatusUpdate = new Timer(true);
		TimerTask statusUpdateTask = new StatusUpdateTask();
		timerStatusUpdate.schedule(statusUpdateTask, 0, 500);
    	
    	shellShip.open();
		while (!shellShip.isDisposed()) 
		{
			if (!display.readAndDispatch())
			{
				display.sleep();
			}
		}
		
		ProxyServer.end();
		hotkey.destroy();
		if (timerLogUpdate != null)
			timerLogUpdate.cancel();
		if (timerStatusUpdate != null)
			timerStatusUpdate.cancel();
		System.exit(0);
	}
}

class LogUpdateTask extends TimerTask
{

	@Override
	public void run() 
	{
		MainWindow.display.asyncExec(new Runnable() 
		{
			public void run() 
			{
				int removeHishoryCount = MainWindow.log.size() - 100;
				for (int i = 0; i < removeHishoryCount; i++)
					MainWindow.log.remove(0);

				int logSize = MainWindow.log.size();
				String displayLog = "";
				for (int i = 0; i < 100 && logSize - i - 1 >= 0; i++)
					displayLog += MainWindow.log.get(logSize - i - 1) + "\r\n";
				MainWindow.txtLog.setText(displayLog);
			}
		});
	}
}

class StatusUpdateTask extends TimerTask
{
	@Override
	public void run() 
	{
		MainWindow.display.asyncExec(new Runnable() 
		{
			public void run() 
			{
				String tokenString = "Token: " + ((MainWindow.kcs.token != null && !MainWindow.kcs.token.equals(""))?"OK":"no");
				MainWindow.lblTokenStatus.setText(tokenString);
				MainWindow.lblTokenStatus.setForeground(MainWindow.display.getSystemColor(SWT.COLOR_BLUE));
				//String versionString = "V: " + ((MainWindow.kcs.referer != null)?(MainWindow.kcs.referer.split("version="))[1]:"null");
				//MainWindow.lblVersionStatus.setText(versionString);
				MainWindow.lblVersionStatus.setForeground(MainWindow.display.getSystemColor(SWT.COLOR_DARK_BLUE));
				if (tokenString.indexOf("OK") > 0 && !MainWindow.btnStart.getEnabled())
				{
					MainWindow.log("Status Init: OK.");
					MainWindow.btnStart.setEnabled(true);
				}
			}
		});
	}
}
